<?php
class SP_Application
{
	private static $app_dir;
	private static $name;
	private static $system_app_config_name='configs/system.php';
	
	const REDIRECT=300;
	const REPLACE=301;
	
	public static function init($name)
	{
		self::$name=$name;
		
		SP_Path::set('app', SP_Config::get('system')->apps_dir.'/'.$name);  //setup path do application directory
		
		if( !is_dir(SP_Path::get('app')) ) //checking for application directory exist
			throw new Exception("Directory for application '$name' not exist");
		
		if( !SP_Config::read('system_app', SP_Path::get('app').self::$system_app_config_name) ) //reading system application config
			throw new Exception('Can\'t read system app config "'.self::$system_app_config_name.'"');

		//setup paths for modules, parts, configs, templates dir
		SP_Path::set('app_modules', SP_Config::get('system_app')->modules_dir, 'app');
		SP_Path::set('app_parts', SP_Config::get('system_app')->parts_dir, 'app');
		SP_Path::set('app_configs', SP_Config::get('system_app')->configs_dir, 'app');
		SP_Path::set('app_templates', SP_Config::get('system_app')->templates_dir, 'app');

		if( !SP_Config::read('app', SP_Path::get('app_configs').SP_Config::get('system_app')->config_name) )  //reading application confid
			throw new Exception('Can\'t read app config "'.SP_Config::get('system_app')->config_name.'"');
		
		if( SP_Config::get('app')->has('model_dir') ) //adding application model dirs to SP_Loader
			SP_Loader::addModelDir(SP_Config::get('app')->model_dir, SP_Path::get('app', false));
		
		if(SP_Config::has('bases') && SP_Config::get('app')->use_database) //initializing SP_Database_BaseCollector
			SP_Database_BaseCollector::fromConfiguration(SP_Config_Configurator::get('bases'));
			
		// initializing Doctrine connections
		if(SP_Config::has('bases') && SP_Config::get('app')->use_database && SP_Config::get('app')->use_doctrine)
		{
			$connections=(array)SP_Config::get('app')->use_doctrine;
			foreach($connections as $conn)
			{
				SP_Database_BaseCollector::getDoctrineConnection($conn);
			}
		}
	}	
	
	public static function start()
	{
		$module=SP_Controller_Route::get();
		if( $module )
		{
			$need_auth=$module->getConfig()->get('need_auth');
			//SP_User::logout();
			if( $need_auth )
			{
				if( !SP_User::checkAccesses($need_auth ) )
				$module=SP_Controller_Route::getLogin();
			}
		}
		else
		{
			$module=SP_Controller_Route::get404();
		}
		//var_dump($module);
		$page = new SP_Controller_Page;
		$page->setModule($module);
		$page->renderModule();
		$page->render();
		$page->show();
	}

}
?>